package controller

import (
	"apitestAfterGo/common"
	"apitestAfterGo/domain"
	"apitestAfterGo/dto"
	"apitestAfterGo/service"
	"apitestAfterGo/utils"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

type UserController struct {
}

func (u *UserController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/getUserById/{id:int}", "GetUserById")
	b.Handle("POST", "/getAllUserByPage/", "GetAllUserByPage")
	b.Handle("POST", "/updateByUserInfo/", "UpdateByUserInfo")
	b.Handle("POST", "/changeStatus/", "ChangeStatus")
	b.Handle("DELETE", "/deleteUser/{id:int}", "DeleteUser")
	b.Handle("GET", "/getAllUser/", "GetAllUser")
}

func (u *UserController) GetUserById(id int) common.Result {
	user, _ := service.UserServiceImpl.GetUserById(id)
	if user.Id != id {
		return utils.Error(common.GetResult(1).Code, common.GetResult(1).Msg)
	}
	return utils.Success(user, "获取当前用户成功!")
}

func (u *UserController) DeleteUser(id int) common.Result {
	user, _ := service.UserServiceImpl.DeleteUser(id)
	return utils.Success(user, "删除用户成功！")
}

func (u *UserController) GetAllUserByPage(dto dto.SearchInputDto) common.Result {
	count, _ := service.UserServiceImpl.CountUsers(dto.Value)
	pages := utils.GetPages(count, dto.PageSize)
	users, _ := service.UserServiceImpl.GetAllUserByPage(dto)
	page := domain.Page{
		Pages:   pages,
		Total:   count,
		Current: dto.Current,
		Size:    dto.PageSize,
		Records: users,
	}
	return utils.Success(page, "获取所有用户成功！")
}

func (u *UserController) UpdateByUserInfo(context iris.Context, userInfo domain.UserDetails) common.Result {
	userInfo.UpdateBy = utils.GetJwtParameter(context, "username").(string)
	_ = service.UserDetailsServiceImpl.UpdateByUserInfo(userInfo)
	return utils.Success(userInfo, "更新用户详情成功!")
}

func (u *UserController) ChangeStatus(context iris.Context, user domain.User) common.Result {
	user.UpdateBy = utils.GetJwtParameter(context, "username").(string)
	status, _ := service.UserServiceImpl.ChangeStatus(user)
	return utils.Success(status, "更新用户状态成功!")
}

func (u *UserController) GetAllUser() common.Result {
	users, _ := service.UserServiceImpl.GetAllUser()
	return utils.Success(users, "获取所有用户成功!")
}
